from flask import Flask,request,jsonify
from config import Config
from flask_cors import CORS
import json
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
CORS(app)
# 设置连接数据库的URL
app.config.from_object(Config)
db = SQLAlchemy(app)


class Role(db.Model):
    # 指定表名
    __tablename__ = 'roles'
    # 定义列对象
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(64), unique=True)
    age = db.Column(db.Integer)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True,autoincrement=True)
    name = db.Column(db.String(64), unique=True)
    sex = db.Column(db.Boolean,default=1)
    add_time = db.Column(db.DateTime)
    content = db.Column(db.Text)
    score = db.Column(db.Float)

# 删除表
# db.drop_all()

# 创建表：
# db.create_all()


@app.route('/add',methods=['POST','GET'])
def add():
    if request.method == 'POST':
        data = json.loads(request.data)
        r = Role(name=data['name'],age=data['age'])
        db.session.add(r)
        db.session.commit()
        return 'ok'

    elif request.method == 'GET':
        r = Role.query.all()
        list=[]
        for i in r:
            dict={}
            dict['name'] = i.name
            dict['age'] = i.age
            list.append(dict)
        return {'code':200,"list":list}


@app.route('/user',methods=['POST','GET'])
def add_user():
    if request.method=='POST':
        data = json.loads(request.data)
        u = User(name=data['name'],add_time=data['add_time'],content=data['content'],score=data['score'])
        db.session.add(u)
        db.session.commit()
        return 'ok'
    elif request.method == 'GET':
        u = User.query.all()
        print(u)
        list = []
        for i in u:
            dict = {}
            dict['name']= i.name
            dict['add_time']= i.add_time
            dict['content']= i.content
            dict['score']= i.score
            list.append(dict)
        return {"code":200,"list":list}






if __name__ == '__main__':
    app.run()
